<template>
  <div
    :class="{ fullscreen: fullscreen }"
    class="tinymce-container"
    :style="{ width: containerWidth }"
  >
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div>
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from './components/EditorImage';
import plugins from './plugins';
import toolbar from './toolbar';
import load from './dynamicLoadScript';

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'

export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function () {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '');
      },
    },
    value: {
      type: String,
      default: '',
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      },
    },
    menubar: {
      type: String,
      default: '',
    },
    height: {
      type: [Number, String],
      required: false,
      default: 487,
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto',
    },
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        en: 'en',
        zh: 'zh_CN',
        es: 'es_MX',
        ja: 'ja',
      },
    };
  },
  computed: {
    containerWidth() {
      const width = this.width;
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        return `${width}px`;
      }
      return width;
    },
  },
  watch: {
    value(val) {
      if (this.hasInit) {
        const editor = window.tinymce.get(this.tinymceId);
        if (editor && val !== editor.getContent()) {
          editor.setContent(val || '');
        }
      }
    },
  },
  mounted() {
    this.init();
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce();
    }
  },
  deactivated() {
    this.destroyTinymce();
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    init() {
      this.initTinymce();
    },
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        base_url: '/tinymce/tinymce.min.js',
        language: this.languageTypeList['zh'],
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        fontsize_formats: '8px 10px 12px 14px 18px 24px 36px',
        placeholder: '请输入内容...',
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        branding: false, // 禁用 "Powered by Tiny"
        statusbar: false, // 禁用状态栏（包括字数统计）
        contextmenu: false,
        contextmenu_never_use_native: true,
        content_style: `
        body {
          background-color: #242424;
          color: #ffffff;
          overflow: auto;
          letter-spacing: 1px;
          font-weight: 300;
          font-size: 12px;
        }
        `,
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value);
          } else {
            editor.getBody().setAttribute('data-placeholder', '请输入内容...'); // 确保占位符生效
          }
          _this.hasInit = true;
          editor.on('NodeChange Change KeyUp SetContent', () => {
            console.log('检测到别忘了刚改了');
            this.hasChange = true;
            this.$emit('input', editor.getContent());
          });
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', e => {
            _this.fullscreen = e.state;
          });
        },
        convert_urls: false,
      });
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId);
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen');
      }

      if (tinymce) {
        tinymce.destroy();
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
    imageSuccessCBK(arr) {
      arr.forEach(v =>
        window.tinymce.get(this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
      );
    },
  },
};
</script>
<style>
.mce-btn {
  background-color: #181818 !important;
  font-size: 12px;
}

.mce-panel {
  background-color: #181818 !important;
  border: 0 !important;
}

.mce-menubar {
  border: 0 !important;
}

.mce-ico {
  color: #f8f0f0 !important;
  font-size: 12px !important;
}

.mce-menubtn button {
  color: #f8f0f0 !important;
}

#tinymce {
  overflow: hidden;
  padding-left: 10px;
}

.mce-content-body {
  overflow: hidden;
}

.mce-menubtn.mce-fixed-width span {
  width: 40px !important;
  font-size: 12px !important;
}

.mce-btn button {
  padding: 3px !important;
  font-size: 12px !important;
}

.mce-toolbar .mce-btn-group {
  padding-left: 10px;
}
</style>
<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
  overflow: auto;
}

.tinymce-container {
  height: 450px;
  overflow: hidden;

  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
  width: 1000px;
  height: 1000px;
}

.editor-custom-btn-container {
  position: absolute;
  left: 360px;
  top: 4px;
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-bottom-button-container {
  position: absolute;
  left: 10px;
  bottom: 4px;
  display: flex;
  justify-content: flex-start;
}

.button {
  border: 1px solid #ababab;
  border-radius: 3px;
  color: #ababab;
  width: 51px;
  height: 22px;
  padding: 5px 13px;
  font-size: 10px;
  margin-right: 15px;
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.button:hover {
  border: 1px solid #414547;
  color: #414547;
}

.fullscreen .editor-bottom-button-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
  position: relative;
  left: 0;
}
</style>
